import React, { useState, useEffect } from 'react';
import {
  Table,
  Button,
  Space,
  Modal,
  Form,
  Input,
  Select,
  message,
  Tag,
  Upload,
} from 'antd';
import {
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  UploadOutlined,
  SearchOutlined,
} from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
import type { UploadProps } from 'antd';
import { importTranslation, getTranslationComponents, createComponent, deleteComponent, editComponent, deleteTranslation, exportTranslation } from '../../api/component';
import { TranslationComponent, TranslationComponentV1 } from '../../types';
import { useSelector, useDispatch } from "react-redux";
import { RootState } from "../../store";
import { getEnableList } from "../../api/language.ts";
import { setLanguagesInfo } from "../../store/slices/languageSlice.ts";

interface Component {
  id: string;
  name: string;
  type: 'text' | 'image' | 'button' | 'input';
  description: string;
  translations: {
    [key: string]: string;
  };
}

const ComponentList: React.FC = () => {
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [form] = Form.useForm();
  const [editingId, setEditingId] = useState<string | null>(null);
  const [components, setComponents] = useState<Component[]>([]);
  const [filteredComponents, setFilteredComponents] = useState<Component[]>([]);
  const [searchText, setSearchText] = useState<string>('');
  const dispatch = useDispatch();

  const { languages } = useSelector((state: RootState) => state.language);

  const [pagination, setPagination] = useState<{ current: number, pageSize: number, total: number }>({
    current: 1,
    pageSize: 10,
    total: 0,
  });

  const refreshComponents = async (page: number = 1, pageSize: number = 10) => {
    try {
      console.log(`Fetching components with page: ${page}, pageSize: ${pageSize}`);
      const response = await getTranslationComponents(page, pageSize);
      console.log('Fetched Components:', response);
      if (response.code === 200) {
        const enableList = await getEnableList();
        dispatch(setLanguagesInfo(enableList));
        setComponents(response.data);
        setFilteredComponents(response.data);
        setPagination({ ...pagination, current: page, pageSize, total: response.total });
      } else {
        message.error('获取组件列表失败');
      }
    } catch (error) {
      message.error('获取组件列表失败');
    }
  };

  useEffect(() => {
    refreshComponents();
  }, []);

  const handleSearch = (e: React.ChangeEvent<HTMLInputElement>) => {
    const text = e.target.value;
    setSearchText(text);
    const filtered = components.filter(component =>
      component.name.toLowerCase().includes(text.toLowerCase()) ||
      component.description.toLowerCase().includes(text.toLowerCase())
    );
    setFilteredComponents(filtered);
  };

  const columns: ColumnsType<Component> = [
    {
      title: '组件名称',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '类型',
      dataIndex: 'type',
      key: 'type',
      render: (type: string) => (
        <Tag color={
          type === 'button' ? 'blue' :
          type === 'text' ? 'green' :
          type === 'image' ? 'purple' :
          'orange'
        }>
          {type ? type.toUpperCase() : 'UNKNOWN'}
        </Tag>
      ),
    },
    {
      title: '描述',
      dataIndex: 'description',
      key: 'description',
    },
    {
      title: '翻译',
      key: 'translations',
      render: (_, record) => (
        <Space size="small">
          {record.translations && Object.entries(record.translations).map(([lang, text]) => (
            <Tag key={lang}>{lang}: {text}</Tag>
          ))}
        </Space>
      ),
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space size="middle">
          <Button
            type="link"
            icon={<EditOutlined />}
            onClick={() => handleEdit(record)}
          >
            编辑
          </Button>
          <Button
            type="link"
            danger
            icon={<DeleteOutlined />}
            onClick={() => handleDelete(record.id)}
          >
            删除
          </Button>
        </Space>
      ),
    },
  ];

  const handleAdd = () => {
    setEditingId(null);
    form.resetFields();
    setIsModalVisible(true);
  };

  const handleEdit = (record: Component) => {
    setEditingId(record.id);
    form.setFieldsValue({
      ...record,
      translations: Object.entries(record.translations).map(([lang, text]) => ({
        lang,
        text,
      })),
    });
    setIsModalVisible(true);
  };

  const handleDelete = (id: string) => {
    Modal.confirm({
      title: '确认删除',
      content: '确定要删除这个组件吗？',
      onOk: async () => {
        try {
          await deleteComponent(id);
          setComponents(components.filter(item => item.id !== id));
          setFilteredComponents(filteredComponents.filter(item => item.id !== id));
          message.success('删除成功');
          refreshComponents();
        } catch (error) {
          message.error('删除失败');
        }
      },
    });
  };

  const handleDeleteTranslation = async (element_id: string, lang_id: string) => {
    Modal.confirm({
      title: '确认删除翻译',
      content: '确定要删除这个翻译吗？',
      onOk: async () => {
        try {
          await deleteTranslation(element_id, lang_id);
          message.success('翻译删除成功');
          refreshComponents();
          setIsModalVisible(false);
        } catch (error) {
          message.error('删除翻译失败');
        }
      },
    });
  };

  const handleModalOk = () => {
    form.validateFields().then(async values => {
      const translations = values.translations.reduce((acc: any, curr: any) => {
        acc[curr.lang] = curr.text;
        return acc;
      }, {});

      let componentData: Partial<TranslationComponentV1> = {
        id: editingId,
        name: values.name,
        type: values.type,
        description: values.description,
        translations,
      };

      try {
        if (editingId) {
          const originalComponent = components.find(component => component.id === editingId);
          if (!originalComponent) {
            message.error('未找到原始组件数据');
            return;
          }

          const updatedFields: Partial<TranslationComponentV1> = {};
          if (originalComponent.name !== componentData.name) {
            updatedFields.name = componentData.name;
          }
          if (originalComponent.type !== componentData.type) {
            updatedFields.type = componentData.type;
          }
          if (originalComponent.description !== componentData.description) {
            updatedFields.description = componentData.description;
          }

          const updatedTranslations: { [key: string]: string } = {};
          for (const lang in translations) {
            if (translations[lang] !== originalComponent.translations[lang]) {
              updatedTranslations[lang] = translations[lang];
            }
          }
          if (Object.keys(updatedTranslations).length > 0) {
            updatedFields.translations = updatedTranslations;
          }

          await editComponent({ id: editingId, ...updatedFields } as TranslationComponentV1);
          message.success('更新成功');
        } else {
          await createComponent(componentData as Omit<TranslationComponent, 'id'>);
          message.success('添加成功');
        }
        refreshComponents();
      } catch (error) {
        message.error((error as any)?.message || '操作失败');
      }
      setIsModalVisible(false);
    }).catch(errorInfo => {
      console.log('表单验证失败:', errorInfo);
    });
  };

  const uploadProps: UploadProps = {
    name: 'file',
    action: 'http://192.168.200.129/lan/v1/element/import ',
    headers: {
      'x-token': localStorage.getItem('token') || '',
    },
    showUploadList: false,
    beforeUpload: (file) => {
      if (!file.name.endsWith('.xlsx')) {
        message.error('仅支持上传 .xlsx 文件');
        return false;
      }
      return true;
    },
    onChange(info) {
      if (info.file.status === 'done') {
        message.success('上传成功');
      } else if (info.file.status === 'error') {
        message.error(`${info.file.name} 上传失败`);
      }
    },
  };

  const handleExport = async () => {
    try {
      const response = await exportTranslation();
      if (response.code === 200) {
        const blob = new Blob([response.data], { type: 'application/octet-stream' });
        const now = new Date();
        const year = now.getFullYear();
        const month = String(now.getMonth() + 1).padStart(2, '0');
        const day = String(now.getDate()).padStart(2, '0');
        const hours = String(now.getHours()).padStart(2, '0');
        const minutes = String(now.getMinutes()).padStart(2, '0');
        const seconds = String(now.getSeconds()).padStart(2, '0');
        const filename = `translations_${year}${month}${day}_${hours}${minutes}${seconds}.xlsx`;

        const url = window.URL.createObjectURL(blob);
        const link = document.createElement('a');
        link.href = url;
        link.setAttribute('download', filename);
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);

        if (response.message) {
          message.success(response.message);
        }
      } else {
        message.error('导出失败');
      }
    } catch (error) {
      message.error('导出失败');
    }
  };

  return (
    <div style={{ padding: '24px', background: '#f0f2f5', minHeight: '100vh' }}>
      <div style={{ maxWidth: '1200px', margin: '0 auto' }}>
        <div style={{
          background: '#fff',
          padding: '24px',
          borderRadius: '2px',
          boxShadow: '0 1px 2px rgba(0, 0, 0, 0.06)'
        }}>
          <div style={{
            display: 'flex',
            justifyContent: 'space-between',
            alignItems: 'center',
            marginBottom: '24px',
            flexWrap: 'wrap',
            gap: '16px'
          }}>
            <h2 style={{ margin: 0 }}>组件管理</h2>
            <Space wrap>
              <Input
                prefix={<SearchOutlined />}
                placeholder="搜索组件名称或描述"
                value={searchText}
                onChange={handleSearch}
                style={{ width: '200px' }}
              />
              <Button
                type="primary"
                icon={<PlusOutlined />}
                onClick={handleAdd}
              >
                添加组件
              </Button>
              <Upload {...uploadProps}>
                <Button icon={<UploadOutlined />}>导入翻译</Button>
              </Upload>
              <Button onClick={handleExport}>导出翻译</Button>
            </Space>
          </div>
          <Table
            columns={columns}
            dataSource={filteredComponents}
            rowKey="id"
            pagination={{
              ...pagination,
              onChange: (page, pageSize) => refreshComponents(page, pageSize),
              showSizeChanger: true,
              showQuickJumper: true,
              showTotal: (total) => `共 ${total} 条记录`,
              responsive: true
            }}
            scroll={{ x: 'max-content' }}
            style={{ overflowX: 'auto' }}
          />
        </div>
      </div>
      <Modal
        title={editingId ? '编辑组件' : '添加组件'}
        open={isModalVisible}
        onOk={handleModalOk}
        onCancel={() => setIsModalVisible(false)}
        width={600}
      >
        <Form
          form={form}
          layout="vertical"
        >
          <Form.Item
            name="name"
            label="组件名称"
            rules={[{ required: true, message: '请输入组件名称' }]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            name="type"
            label="类型"
            rules={[{ required: true, message: '请选择组件类型' }]}
          >
            <Select>
              <Select.Option value="text">文本</Select.Option>
              <Select.Option value="button">按钮</Select.Option>
              <Select.Option value="input">输入框</Select.Option>
              <Select.Option value="image">图片</Select.Option>
            </Select>
          </Form.Item>
          <Form.Item
            name="description"
            label="描述"
          >
            <Input.TextArea />
          </Form.Item>
          <Form.List name="translations">
            {(fields, { add }) => (
              <>
                {fields.map(({ key, name, ...restField }) => (
                  <div key={key} style={{
                    display: 'flex',
                    marginBottom: 16,
                    flexWrap: 'wrap',
                    gap: '8px'
                  }}>
                    <Form.Item
                      {...restField}
                      name={[name, 'lang']}
                      rules={[{ required: true, message: '请选择语言' }]}
                      style={{ marginBottom: 0, minWidth: '120px' }}
                    >
                      <Select placeholder="选择语言">
                        {languages.map(lang => (
                          <Select.Option
                            key={lang.id}
                            value={lang.id}
                          >
                            {lang.name} ({lang.id})
                          </Select.Option>
                        ))}
                      </Select>
                    </Form.Item>
                    <Form.Item
                      {...restField}
                      name={[name, 'text']}
                      rules={[{ required: true, message: '请输入翻译文本' }]}
                      style={{ marginBottom: 0, flex: 1, minWidth: '200px' }}
                    >
                      <Input placeholder="翻译文本" />
                    </Form.Item>
                    <Button type="link" danger onClick={() => {
                      const lang_id = form.getFieldValue(['translations', name, 'lang']);
                      handleDeleteTranslation(editingId!, lang_id);
                    }} style={{ marginBottom: 0 }}>删除</Button>
                  </div>
                ))}
                <Form.Item>
                  <Button type="dashed" onClick={() => add()} block icon={<PlusOutlined />}>
                    添加翻译
                  </Button>
                </Form.Item>
              </>
            )}
          </Form.List>
        </Form>
      </Modal>
    </div>
  );
};

export default ComponentList;